<template>
  <div class="billingRuleManagement-page">
    <breadcrumb />
    <div class="search-container">
      <Search @search="getSearchParams" />
    </div>
    <div class="table-container" v-for="item in table.data" :key="item.id">
      <div class="table-content">
        <div class="row">
          <div class="icon"></div>
          <div class="ruleName">{{ item.ruleName }}</div>
        </div>
        <div class="submit-btns">
          <div></div>
          <div class="submit-btns-right">
            <el-button
              type="primary"
              class="submit-btn-road"
              @click="roadSectionData(item)"
            >
              关联路段</el-button
            >
            <el-button
              type="primary"
              class="submit-btn-edit"
              @click="editData(item)"
            >
              编辑</el-button
            >
            <el-button
              type="primary"
              class="submit-btn-del"
              @click="deleteData(item)"
            >
              删除</el-button
            >
          </div>
        </div>
      </div>
      <div class="row row-content">
        <div class="title">免费时长:{{ item.freeDuration }}</div>
        <div class="title" style="margin-left: 16px">
          单日收费上限:{{ item.dayLimit }}
        </div>
      </div>
      <div class="table">
        <el-table
          :data="item.list"
          :loading="table.loading"
          style="width: 100%"
          :span-method="dynamicSpanMethod"
          :header-cell-style="spanHeader2"
          :cell-style="{
            'font-size': '14px',
            'font-weight': 400,
            color: '#333333',
          }"
          border
        >
          <el-table-column
            prop="billingDateType"
            label="日期类型"
            align="center"
            min-width="90"
          />
          <el-table-column
            prop="vehicleType"
            label="车辆类型"
            align="center"
            min-width="90"
          />
          <el-table-column
            prop="timeFrame"
            label="规则明细"
            align="center"
            min-width="160"
          />
          <el-table-column prop="rateDesc" min-width="220" />
          <el-table-column prop="timeLimit" min-width="80" />
          <template #empty>
            <el-empty :image="imgNone" />
          </template>
        </el-table>
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="title"
        destroy-on-close
        :before-close="handleClose"
        :close-on-click-modal="false"
        :width="670"
      >
        <component
          :is="componentTag"
          @operationDone="operationDone"
          :operationId="operationId"
        >
        </component>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import breadcrumb from "@/components/breadcrumb/index.vue";
import Search from "./components/search.vue";
const imgNone = new URL("@/assets/image/imgNone.png", import.meta.url).href;
import deleteComponent from "./components/deleteComponent.vue";
import roadSectionComponent from "./components/roadSectionComponent.vue";
import { ref, reactive, shallowRef } from "vue";
import { getBillingRules } from "./request.js";

import { useRouter } from "vue-router";

const router = useRouter();

// 搜索
const searchModel = ref({
  keyword: "",
});

const getSearchParams = (value) => {
  console.log(value);
  if (value.operation === 3) {
    addData();
  } else {
    searchModel.value = value;
    getData();
  }
};

// 弹窗
const title = ref("");
const dialogVisible = ref(false);
const componentTag = shallowRef("");
const operationId = ref("");
const operationDone = (r) => {
  dialogVisible.value = false;
  operationId.value = "";
  if (!r) {
    getData();
  }
};

const handleClose = () => {
  dialogVisible.value = false;
};

const spanHeader2 = ({ row, column, rowIndex, columnIndex }) => {
  let comStyle = {
    background: "#F1F1F1",
    "font-size": "14px",
    "font-weight": 600,
    color: "#333333",
  };
  // 1.1 让第0行的第0列跨2行
  if (rowIndex === 0) {
    row[2].colSpan = 3; // 将表头第二列和第三列合并，内容展示为第二列的内容
    if (columnIndex === 3) {
      // 将表头第一列隐藏
      return {
        display: "none",
      };
    }
    if (columnIndex === 4) {
      // 将表头第一列隐藏
      return {
        display: "none",
      };
    }
  }
  return comStyle;
};

const namerowspan = ref("");

const dynamicSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // console.log("column ===>", column);
  // console.log("rowIndex ===>", rowIndex);
  if (columnIndex === 0) {
    if (rowIndex % 9 === 0) {
      return {
        rowspan: 9,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
  if (columnIndex === 1) {
    if (rowIndex % 3 === 0) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

// 新增按钮
const addData = () => {
  router.push("/road/config/chargingRule/add");
};

// 编辑按钮
const editData = (row) => {
  // 将对象转换为 JSON 字符串
  const rowDataJson = JSON.stringify(row.id);
  console.log(rowDataJson, "aaaaaaaaaa");
  router.push({
    path: "/road/config/chargingRule/edit",
    query: {
      data: encodeURIComponent(rowDataJson),
    },
  });
};

// 删除按钮
const deleteData = (row) => {
  title.value = "温馨提示";
  operationId.value = row;
  componentTag.value = deleteComponent;
  dialogVisible.value = true;
};

// 关联路段
const roadSectionData = (row) => {
  title.value = `配置[${row.ruleName}]关联路段`;
  operationId.value = row;
  componentTag.value = roadSectionComponent;
  dialogVisible.value = true;
};

// 表格
const table = reactive({
  data: [],
  total: 0,
  loading: true,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50],
});

const handleCurrentChange = (value) => {
  pagination.currentPage = value;
  getData();
};

const handleSizeChange = (value) => {
  pagination.pageSize = value;
  getData();
};

const getData = async () => {
  await getBillingRules(searchModel.value.keyword).then((res) => {
    console.log("res ===>", res);
    if (res.data.code === 0) {
      table.data = res.data.result;
      let data = res.data.result;
      let resuleData = [];
      data.forEach((item) => {
        // console.log("item ===>", item);

        item.dateTypes.forEach((dateType) => {
          dateType.vehicleTypes.forEach((vehicle) => {
            vehicle.ruleRateVos.forEach((ruleRate) => {
              // console.log("ruleRate ===>", ruleRate);

              let data = {
                timeFrame: ruleRate.timeFrame,
                rateDesc: ruleRate.rateDesc,
                timeLimit:
                  ruleRate.timeLimit > 0
                    ? ruleRate.timeLimit + "元封顶"
                    : "不封顶",
                dayLimit: item.dayLimit > 0 ? item.dayLimit : "不封顶",
                vehicleType:
                  vehicle.vehicleType == 1
                    ? "大型车"
                    : vehicle.vehicleType == 2
                    ? "小型车"
                    : "新能源",
                billingDateType:
                  dateType.billingDateType == 1 ? "工作日" : "非工作日",
                freeDuration: item.freeDuration,
                ruleName: item.ruleName,
                id: item.id,
              };
              resuleData.push(data);
            });
          });
        });
      });
      const grouped = {};
      resuleData.forEach((item) => {
        if (!grouped[item.id]) {
          grouped[item.id] = {
            id: item.id,
            ruleName: item.ruleName,
            freeDuration: item.freeDuration,
            dayLimit: item.dayLimit,
            list: [],
            listLength: 0,
          };
        }
        const { id, ruleName, freeDuration, dayLimit, ...otherProps } = item;
        grouped[item.id].list.push(otherProps);
        grouped[item.id].listLength = grouped[item.id].list.length / 2;
      });
      table.data = Object.values(grouped);
      console.log("table.data ===>", table.data);

      table.loading = false;
    }
  });
};

getData();
</script>

<style lang="less" scoped>
.billingRuleManagement-page {
  .search-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px 24px 8px 24px;
    background: #fff;
    border-radius: 6px;
  }
  .table-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px;
    background: #fff;
    border-radius: 6px;
    .table-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 2px solid #cccccc;
      padding-bottom: 10px;
      .icon {
        width: 6px;
        height: 24px;
        background: #007aff;
      }
      .ruleName {
        font-weight: 600;
        font-size: 20px;
        color: #333333;
        margin-left: 12px;
      }
      .submit-btns {
        display: flex;
        justify-content: space-between;
      }
      .submit-btns-right {
        display: flex;
      }
      .submit-btn-road {
        color: #13cc4e;
        background-color: #ffffff;
        border: 1px solid #13cc4e;
        border-radius: 2px;
        margin-left: 13px;
        padding: 5px 9px;
        font-weight: 400;
        font-size: 16px;
        color: #15c34c;
      }
      .submit-btn-edit {
        color: #007aff;
        background-color: #ffffff;
        border: 1px solid #007aff;
        border-radius: 2px;
        margin-left: 13px;
        padding: 5px 9px;
        font-weight: 400;
        font-size: 16px;
        color: #007aff;
      }
      .submit-btn-del {
        color: #333333;
        background-color: #ffffff;
        border: 1px solid #333333;
        border-radius: 2px;
        margin-left: 13px;
        padding: 5px 9px;
        font-weight: 400;
        font-size: 16px;
        color: #333333;
      }
    }
    .row-content {
      margin-top: 24px;
      .title {
        background: #eef6ff;
        border-radius: 1px;
        border: 1px solid #bfdeff;
        padding: 5px 14px;
        font-weight: 600;
        font-size: 16px;
        color: #333333;
      }
    }
    .table {
      margin-top: 32px;
    }
  }
  .row {
    display: flex;
    align-items: center;
  }
}
</style>